package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//获取池
//获取连接
//创建statement
//执行sql
//返回结果集分析
//行映射
@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dateSource;


    @Override
    public List<Map<String, Object>> findGoods() {
        Connection con = null;
        Statement stmt = null;
        String sql = "select * from tb_goods";
        ResultSet rs = null;
        try {
            //获取池
             con = dateSource.getConnection();
            //获取连接
             stmt = con.createStatement();
            //执行sql
             rs = stmt.executeQuery(sql);
             List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
             while (rs.next()){
                 Map<String,Object> map = new HashMap<>();
                 int id = rs.getInt("id");
                 String name = rs.getString("name");
                 String remark = rs.getString("remark");
                 String createdTime = rs.getString("createdTime");
                 map.put("id", id);
                 map.put("name", name);
                 map.put("remark", remark);
                 map.put("createdTime", createdTime);
                 list.add(map);
//                 System.out.println(map);
             }
             return list;

        } catch (SQLException e) {
            e.printStackTrace();
//            return null;
            throw new RuntimeException("数据查询失败"+e.getMessage());
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException throwables) {throwables.printStackTrace();}}
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }


        }

        //创建statement
        //执行sql
        //返回结果集分析
        //行映射

//        return null;
    }
}


